import {
  getCurrentSong,
  getLyrics
} from "services/player"

import { getRandom } from 'utils/math-util'
import { parseLyrics } from 'utils/parse-lyrics'

import  * as actionTypes from './constants'

const changeCurrentSongAction = (currentSong) => ({
  type: actionTypes.CHANGE_CURRENT_SONG,
  currentSong
})

const changePlayListAction = (playList) => ({
  type: actionTypes.CHANGE_PLAY_LIST,
  playList
})

const changeCurrentSongIndexAction = (index) => ({
  type: actionTypes.CHANGE_CURRENT_SONG_INDEX,
  index
})

const changeLyricsListAction = (lyricsList) => ({
  type: actionTypes.CHANGE_LYRICS_LIST,
  lyricsList
})

export const changeSequenceAction = (sequence) => ({
  type: actionTypes.CHANGE_SEQUENCE,
  sequence
})

export const changeCurrentLyricsIndexAction = (index) => ({
  type: actionTypes.CHANGE_CURRENT_LYRICS_INDEX,
  index
})

export const changeCurrentIndexSongAction = (tag) => {
  return (dispatch, getState) => {
    const playList = getState().getIn(['player', 'playList'])
    const sequence = getState().getIn(['player', 'sequence'])
    let currentSongIndex = getState().getIn(['player', 'currentSongIndex'])

    switch(sequence) {
      case 1: //随机播放
        let randomIndex = -1
        while(randomIndex === currentSongIndex) {
          randomIndex = getRandom(playList.length)
        }
        currentSongIndex = getRandom(playList.length)
        break
      default:
        currentSongIndex += tag
        if(currentSongIndex >= playList.length) currentSongIndex = 0
        if(currentSongIndex < 0) currentSongIndex = playList.length - 1
    }

    const currentSong = playList[currentSongIndex]
    dispatch(changeCurrentSongAction(currentSong))
    dispatch(changeCurrentSongIndexAction(currentSongIndex))
  }
}

export const getSongDetailAction = (ids) => {
  return (dispatch, getState) => {
    // 1.根据id查找playList中是否有该歌曲
    const playList = getState().getIn(['player', 'playList'])
    const songIndex = playList.findIndex(song => song.id === ids)

    // 2.判断是否找到歌曲
    let song = null
    if(songIndex !== -1) {
      dispatch(changeCurrentSongIndexAction(songIndex))
      dispatch(changeCurrentSongAction(playList[songIndex]))
      dispatch(getLyricsAction(song.id))
    } else {
      // 请求歌曲数据
      getCurrentSong(ids).then(res => {
        song = res.songs && res.songs[0]
        if(!song) return

        // 将请求数据放入播放列表
        const newPlayList = [...playList]
        newPlayList.push(song)

        // 更新redux中的值
        dispatch(changePlayListAction(newPlayList))
        dispatch(changeCurrentSongIndexAction(newPlayList.length - 1))
        dispatch(changeCurrentSongAction(song))

        // 3.请求该歌曲的歌词
        if(!song) return
        dispatch(getLyricsAction(song.id))
      })
    }
  }
}

export const getLyricsAction = (id) => {
  return dispatch => {
    getLyrics(id).then(res => {
      const lyricsList = parseLyrics(res.lrc.lyric)
      dispatch(changeLyricsListAction(lyricsList))
    })
  }
}